package com.sunwhite.herostore.config.mq;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/***
 * mQ消息生产者
 */
public class MQProducer {
    /**
     * 日志对象
     */
    static private final Logger log = LoggerFactory.getLogger(MQProducer.class);

    /**
     * 生产者
     */
    static private DefaultMQProducer producer = null;

    /**
     * 私有化类默认构造器
     */
    private MQProducer() {
    }

    /**
     * 初始化
     */
    public static void init(){
        try {
            //创建生产者
            DefaultMQProducer producer = new DefaultMQProducer("herostore");
            //设置 nameServer 地址
            producer.setNamesrvAddr("119.3.228.251:9876");

            //启动生产者
            producer.start();
            producer.setRetryTimesWhenSendAsyncFailed(3);
        } catch (MQClientException e) {
            log.error(e.getMessage(),e);
        }
    }

    /**
     * 发送消息
     */
    public static void sendMsg(String topic ,Object msg){
        if (null==topic||msg==null){
            return;
        }

        if (null==producer){
            throw new RuntimeException("producer 尚未初始化！");
        }

        Message message = new Message();
        message.setTopic(topic);
        message.setBody(JSONObject.toJSONBytes(msg));

        try {
            producer.send(message);
        } catch (Exception e) {
           log.error(e.getMessage(),e);
        }

    }

}
